package com.zallds.watermark;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.io.Serializable;
import java.time.Duration;


/**
 * 有序流的Watermark案例演示
 * 使用滚动计时窗口，计算安放在北京西站各个监测点的红外测温仪，每隔3秒钟，所探测到的旅客的平均体温。
 * <p>
 * 使用有序流的watermark
 * 每个窗口最大允许的乱序时间是10s
 * 时间语义选用EventTime
 */
public class WatermarkAllowedLatenessDemo2 {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.socketTextStream("192.168.62.37", 8889)
//                .filter(keyword -> StringUtils.isNotEmpty(keyword))
                .map(new Splitter())
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Order>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((order, timestamp) -> order.getEventTime())
                ).keyBy(Order::getName)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .allowedLateness(Time.seconds(3))
                .sum("money")
                .print();
        env.execute();

    }

    private static class Splitter implements MapFunction<String, Order> {
        @Override
        public Order map(String value) throws Exception {
            String name = value.split(" ")[0];
            Integer money = Integer.parseInt(value.split(" ")[1]);
            Long eventTime = Long.parseLong(value.split(" ")[2]);
            return new Order(name, money, eventTime);
        }
    }


    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Order implements Serializable {
        private String name;
        private Integer money;
        private Long eventTime;

    }


}
